package com.video.main_video.common.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    /**
     * 生成token  header.payload.singature
     */
    private static final String SING = "717293846@qq.com";

    public static String getToken(Map<String, String> map) {

        Calendar instance = Calendar.getInstance();
        // 默认7天过期
        instance.add(Calendar.DATE, 7);

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        // payload
        map.forEach(builder::withClaim);
        String token = builder.withExpiresAt(instance.getTime())  //指定令牌过期时间
                .sign(Algorithm.HMAC256(SING));  // sign
        return token;
    }

    /**
     * 验证token  合法性
     * @return
     */
    public static DecodedJWT verify(String token) {
        try {
            return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        } catch (JWTVerificationException e) {
            return null;
        }
    }

    /**
     * 获取token信息方法
     */
    /*public static DecodedJWT getTokenInfo(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        return verify;
    }*/
    public static void main(String[] args) {
        HashMap<String, String> user = new HashMap<String, String>();
        user.put("user", "hello");
        String token = "        System.out.println(\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6ImFkbWluIiwidXNlck5hbWUiOiJhZG1pbiIsImV4cCI6MTY3NjQ2ODI4MiwidXNlcklkIjoiY2RhMTllNjRhM2ZkNDczZWIwOTllNzY0ZmZmNzYxZDMifQ.7LFL-mrIKUtTBbaMiNSBjPl6bCmvl_Bi3nbDKvzxiGM com.auth0.jwt.JWTDecoder@4874d1da";

        System.out.println("");
        DecodedJWT verify = JwtUtils.verify(token);
        System.out.println(verify.getClaim("user").asString());

    }
}


